package com.magenta.maxoptra.gis.distancematrix.commands;

import com.magenta.maxoptra.gis.distancematrix.*;

/**
 * @author Sergey Grachev
 */
final class ForceMatrixUpdate extends AbstractGroupCommand {

    private final long matrixId;
    private boolean requireMatrixUpdating;

    ForceMatrixUpdate(final long groupId, final long matrixId) {
        super(groupId);
        this.matrixId = matrixId;
    }

    @Override
    public CommandType getType() {
        return CommandType.FORCE_MATRIX_UPDATE;
    }

    @Override
    public void execute(final DistanceMatrixDAO db, final DistanceMatrixServiceProxy service) {
        requireMatrixUpdating = !db.isMatrixFullyCalculated(groupId, matrixId);

        if (requireMatrixUpdating) {
            final long priority = System.currentTimeMillis();
            if (db.setMatrixPriority(groupId, matrixId, priority)) {
                service.changeMatrixPriority(groupId, matrixId, priority);
            }
        } else {
            service.notifyMatrixUpdateFinished(groupId, matrixId, UpdateResultType.UPDATED);
        }
    }

    @Override
    public boolean isRequireGroupLock() {
        return true;
    }

    @Override
    public UpdateRequestType isRequireMatrixUpdating() {
        return requireMatrixUpdating ? UpdateRequestType.IMMEDIATELY : UpdateRequestType.NONE;
    }

    @Override
    public String toString() {
        return "ForceMatrixUpdate{" +
                "groupId=" + groupId +
                ", matrixId=" + matrixId +
                '}';
    }
}
